package com.example.androidstudy.ui.know

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.androidstudy.databinding.ItemDefaultBinding

class KnowAdapter : ListAdapter<AssetInfo, KnowVH>(diff) {
    companion object {
        val diff = object : DiffUtil.ItemCallback<AssetInfo>() {
            override fun areItemsTheSame(oldItem: AssetInfo, newItem: AssetInfo): Boolean {
                return oldItem == newItem
            }

            override fun areContentsTheSame(oldItem: AssetInfo, newItem: AssetInfo): Boolean {
                return oldItem == newItem
            }

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KnowVH {
        return KnowVH(
            ItemDefaultBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: KnowVH, position: Int) {
        holder.onBind(getItem(position))
    }
}

class KnowVH(
    private val binding: ItemDefaultBinding,
    private val knowAdapter: KnowAdapter = KnowAdapter()
) : RecyclerView.ViewHolder(
    binding.root
) {

    init {
        binding.apply {
            rcChildren.adapter = knowAdapter
            rcChildren.layoutManager = LinearLayoutManager(rcChildren.context)
        }
    }

    fun onBind(item: AssetInfo) {
        binding.apply {
            bt.text = item.description
            bt.setOnClickListener {
                if (item.children.isEmpty()) {
                    bt.findNavController()
                        .navigate(
                            KnowFragmentDirections.actionNavigationKnowToTextFragment(
                                item.path,
                                item.description
                            )
                        )
                } else {
                    if (rcChildren.visibility == View.VISIBLE) {
                        rcChildren.visibility = View.GONE
                    } else {
                        rcChildren.visibility = View.VISIBLE
                    }
                }
            }
            if (item.children.isNotEmpty()) {
                knowAdapter.submitList(item.children)
            }
        }
    }

}